package com.photovoltaic.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photovoltaic.auth.entity.Permission;
import com.photovoltaic.auth.security.services.UserDetailsImpl;
import com.photovoltaic.auth.service.OperationLogService;
import com.photovoltaic.auth.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/auth/permissions")
@RequiredArgsConstructor
public class PermissionController {
    
    private final PermissionService permissionService;
    private final OperationLogService operationLogService;
    
    @GetMapping
    @PreAuthorize("hasAuthority('permission:list')")
    public ResponseEntity<Page<Permission>> getPermissions(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Permission::getPermissionName, name);
        }

        Page<Permission> page = permissionService.page(new Page<>(current, size), queryWrapper);
        return ResponseEntity.ok(page);
    }
    
    @GetMapping("/types/{type}")
    @PreAuthorize("hasAuthority('permission:list')")
    public ResponseEntity<List<Permission>> getPermissionsByType(@PathVariable Integer type) {
        List<Permission> permissions = permissionService.findByType(type);
        return ResponseEntity.ok(permissions);
    }
    
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('permission:view')")
    public ResponseEntity<Permission> getPermissionById(@PathVariable Integer id) {
        Permission permission = permissionService.getById(id);
        if (permission == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(permission);
    }
    
    @PostMapping
    @PreAuthorize("hasAuthority('permission:add')")
    public ResponseEntity<Permission> createPermission(
            @RequestBody Permission permission,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = permissionService.save(permission);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "PERMISSION_CREATE",
                "创建权限: " + permission.getPermissionName(),
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(permission);
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('permission:edit')")
    public ResponseEntity<Permission> updatePermission(
            @PathVariable Long id,
            @RequestBody Permission permission,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        permission.setId(id);
        boolean success = permissionService.updateById(permission);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "PERMISSION_UPDATE",
                "更新权限: " + permission.getPermissionName(),
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(permission);
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('permission:delete')")
    public ResponseEntity<Map<String, Object>> deletePermission(
            @PathVariable Integer id,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = permissionService.removeById(id);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "PERMISSION_DELETE",
                "删除权限: ID=" + id,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
} 